import getdatah
import pandas as pd
import matplotlib.pyplot as plt
from flask import Flask, redirect, render_template, request
import plotly.graph_objs as go
import pandas as pd
import io
import base64
import plotly.express as px
from flask import Flask, render_template, request, jsonify
import pandas as pd
import pre
import numpy as np
from flask import Flask, send_file
import io
import datetime

app = Flask(__name__)

@app.route('/visual', methods=['GET', 'POST'])
def visualize():
    global df
    if request.method == 'POST':
        column_name = request.form['column_name']
        chart_type = request.form['chart_type']
        if chart_type == 'line':
            fig = px.line(df, x=df.index, y=column_name, title=f'{column_name} Trend')
        elif chart_type == 'bar':
            fig = px.bar(df, x=df.index, y=column_name, title=f'{column_name} Distribution')
        elif chart_type == 'scatter':
            fig = px.scatter(df, x=df.index, y=column_name, title=f'{column_name} Scatter Plot')
        elif chart_type == 'box':
            fig = px.pie(df, values=column_name, names=df.index, title=f'{column_name} pie Chart')
        
        plot_data = fig.to_json()
        return jsonify({'plotData': plot_data, 'title': fig.layout.title.text})
    
    cityname = request.args.get('cityname')
    df = getdatah.translate_column_names(cityname)
    columns = list(df.columns)
    return render_template('index.html', columns=columns)

@app.route('/prewea', methods=['GET'])
def prewea():
    cityname = request.args.get('cityname')
    predicted_values, future_dates_list = pre.getpre(cityname)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    # 创建一个图形
    plt.figure(figsize=(10, 6))

    # 绘制最低温度曲线
    plt.plot(future_dates_list, predicted_values[:,0], label='最低温度')
    # 绘制最高温度曲线
    plt.plot(future_dates_list, predicted_values[:,1], label='最高温度')
    # 设置x轴刻度间隔为每隔5天显示一个刻度
    plt.xticks(future_dates_list[::5])
    # 添加图例
    plt.legend()
    # 添加标题和坐标轴标签
    plt.title('最低温度和最高温度随时间变化')
    plt.xlabel('日期')
    plt.ylabel('温度')
    
    # 保存图像为png格式，并转换为base64编码
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    img_data = base64.b64encode(buf.read()).decode('utf-8')
    
    return render_template('prewea.html', img_data=img_data)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000,debug=True)